package com.example.demo.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DashboardVerifyController {

    // 控制面板访问密码
    private static final String DASHBOARD_PASSWORD = "admin123";
    private static final String VERIFICATION_ATTRIBUTE = "dashboard_verified";

    @GetMapping("/verify-dashboard")
    public String showVerificationPage(@RequestParam(value = "redirectUrl", required = false) String redirectUrl, 
                                      Model model) {
        // 默认重定向到dashboard主页
        if (redirectUrl == null || redirectUrl.isEmpty()) {
            redirectUrl = "/dashboard";
        }
        
        model.addAttribute("redirectUrl", redirectUrl);
        return "verify-dashboard";
    }
    
    @PostMapping("/verify-dashboard")
    public String verifyDashboardAccess(@RequestParam("password") String password,
                                       @RequestParam(value = "redirectUrl", required = false) String redirectUrl,
                                       HttpSession session) {
        // 检查密码是否正确
        if (DASHBOARD_PASSWORD.equals(password)) {
            // 在会话中记录验证状态
            session.setAttribute(VERIFICATION_ATTRIBUTE, true);
            
            // 重定向到目标URL
            if (redirectUrl == null || redirectUrl.isEmpty()) {
                return "redirect:/dashboard";
            }
            return "redirect:" + redirectUrl;
        } else {
            // 密码错误，返回验证页面
            return "redirect:/verify-dashboard?error&redirectUrl=" + (redirectUrl != null ? redirectUrl : "");
        }
    }
    
    /**
     * 检查用户是否已通过控制面板验证
     * @param session 当前会话
     * @return 是否已验证
     */
    public static boolean isDashboardVerified(HttpSession session) {
        Object verified = session.getAttribute(VERIFICATION_ATTRIBUTE);
        return verified != null && (Boolean) verified;
    }
    
    /**
     * 清除控制面板验证状态
     * @param session 当前会话
     */
    public static void clearDashboardVerification(HttpSession session) {
        session.removeAttribute(VERIFICATION_ATTRIBUTE);
    }
} 